package com.qipay.api.qq.controller.v1;

import com.qipay.api.qq.controller.v1.vo.CpPayQQNativeVo;
import com.qipay.pay.QQPayService;
import com.qipay.pay.entity.CpPayQQNativeRequest;
import com.qipay.scalar.type.ApiStatusEnum;
import com.qipay.security.jwt.JWTUser;
import com.qipay.utils.ResultUtils;
import com.qipay.utils.XmlUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("/sig/v1/qq")
public class QQScanCodeController {
    @Value("${api.response.sign.name}")
    String apiResponseSignName;

    @Value("${api.response.key.name}")
    String apiResponseKeyName;

    @Autowired
    QQPayService qqPayService;

    @RequestMapping(value = "/native", method = RequestMethod.POST, produces = {"application/xml;charset=UTF-8"})
    private String unionCreate(
            HttpServletRequest request,
            HttpServletResponse response,
            @AuthenticationPrincipal JWTUser user
    ) throws Exception {

        Map<String, Object> params = (Map<String, Object>) request.getAttribute("params");
        CpPayQQNativeVo vo = (CpPayQQNativeVo) XmlUtils.mapToBean(
                params, CpPayQQNativeVo.class);
        CpPayQQNativeRequest bean = new CpPayQQNativeRequest();
        BeanUtils.copyProperties(vo, bean);

        Map<String, Object> result = qqPayService.payQQNative(bean, user);

        Assert.notNull(result,
                ResultUtils.buildErrorMsg(ApiStatusEnum.SERVICE_BUSY, ApiStatusEnum.SERVICE_BUSY.getInfo()));

        result = ResultUtils.wrapResult(ApiStatusEnum.OK.getCode().toString(), null, result);
        result = ResultUtils.signResult(result, user.getSecret(), apiResponseSignName, apiResponseKeyName);
        return XmlUtils.toString(result, "xml");

    }
}
